import json

import requests

from app import redisclient,RedisClient
from app.config.secure import gzh_appid,gzh_appsecret

# redisclient = RedisClient()
class gzh_qrcode(object):

    def __init__(self):
        self.token = getGZHToken()
        self.mpToken = getMpToken()
        self.qrcode_url = f'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={self.token}'
        self.mp_qrcode_url = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={self.mpToken}'

    def qrcode_ticket(self, scene_id):
        # ticket = redisclient.GetQRCodeTicket()
        # if ticket:
        #     return ticket
        data = {
            "expire_seconds": 604800,
            "action_name": "QR_STR_SCENE",
            "action_info":
                {
                    "scene": {"scene_str": f'samereport_login##{scene_id}'}
                }
        }
        res = requests.post(self.qrcode_url, data=json.dumps(data))

        if res.status_code == 200:
            qr_data = json.loads(res.text)
            ticket = qr_data['ticket']
            redisclient.setQRCodeTicket(ticket, qr_data['expire_seconds'])
            return ticket
        else:
            print(res.text)
            return None

    def unlock_ai_qrcode_ticket(self, order_number):
        data = {
            "expire_seconds": 604800,
            "action_name": "QR_STR_SCENE",
            "action_info":
                {
                    "scene": {"scene_str": f'unlock_ai##{order_number}'}
                }
        }
        res = requests.post(self.qrcode_url, data=json.dumps(data))
        if res.status_code == 200:
            qr_data = json.loads(res.text)
            ticket = qr_data['ticket']
            return ticket
        else:
            print(res.text)
            return None
    
    def unlock_aigc_qrcode_ticket(self, order_number):
        data = {
            "expire_seconds": 604800,
            "action_name": "QR_STR_SCENE",
            "action_info":
                {
                    "scene": {"scene_str": f'unlock_aigc##{order_number}'}
                }
        }
        res = requests.post(self.qrcode_url, data=json.dumps(data))

        if res.status_code == 200:
            qr_data = json.loads(res.text)
            ticket = qr_data['ticket']
            return ticket
        else:
            print(res.text)
            return None

    def mp_qrcode(self, scene):
        data = {
            'scene': scene,
            'page': 'pages/share/share',
            'width': 128
        }
        r = requests.post(self.mp_qrcode_url, data=json.dumps(data))
        if r.status_code == 200:

            return r.content


def getGZHToken():
    token = redisclient.GetGZHToken()
    if token:
        return token
    url = 'https://api.weixin.qq.com/cgi-bin/stable_token'
    data = {
        "grant_type": "client_credential",
        "appid": gzh_appid,
        "secret": gzh_appsecret
    }
    res = requests.post(url=url, data=json.dumps(data), verify=False)
    if res.status_code == 200:
        res_data = json.loads(res.text)
        access_token = res_data['access_token']
        expire = res_data['expires_in']
        print(expire)
        redisclient.setGZHToken(access_token, expire)
        return access_token
    else:
        return None


def getMpToken():
    token = redisclient.GetMPToken()
    if token:
        return token
    url = f'https://api.weixin.qq.com/cgi-bin/token?appid=wxe714527bc5c7ec08&secret=deeb49c705fc7fbfcf73fa3a374b7621&grant_type=client_credential'
    # data = {
    #     "grant_type": "client_credential",
    #     "appid": "wxe714527bc5c7ec08",
    #     "secret": "deeb49c705fc7fbfcf73fa3a374b7621"
    # }
    res = requests.get(url=url, verify=False)
    if res.status_code == 200:
        res_data = json.loads(res.text)
        access_token = res_data['access_token']
        expire = res_data['expires_in']
        redisclient.setMPToken(access_token, expire)
        return access_token
    else:
        return None


'''
    <xml>
        <ToUserName><![CDATA[gh_bb2a445a3d55]]></ToUserName>
        <FromUserName><![CDATA[oWInjwiOIKeLxKjC1vbkSytIkbXc]]></FromUserName>
        <CreateTime>1702389829</CreateTime>
        <MsgType><![CDATA[event]]></MsgType>
        <Event><![CDATA[SCAN]]></Event>
        <EventKey><![CDATA[test]]></EventKey>
        <Ticket><![CDATA[gQH-7zwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyTE9idkJabzlmejIxQzNxMWhCY0gAAgQDIHhlAwSAOgkA]]></Ticket>
    </xml>
'''

if __name__ == '__main__':
    bot = gzh_qrcode()
    print(bot.mp_qrcode('111'))
